<?php

class NCore_MailAction implements NCore_IAction
{
	protected $subject;
	protected $message;
	protected $to;
	protected $headers = array();
	protected $hackemes = array('content-type:','charset=','mime-version:','multipart/mixed','bcc:', 'cc:', "\r", "\n");
	protected $emailRegex = '/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/';

	function __construct()
	{
	
	}
	public function withSubject($subject)
	{
		if($this->isFreeOfHackemes($subject))
		{
			$this->subject = $subject;
			return $this;
		}
		else
		{
			throw new Exception('The \'subject\' was not valid.');
		}
	}
	public function withMessage($message)
	{
		// message lines should not be longer than 70 chars
		$this->message = wordwrap($message, 70);
		return $this;
	}
	public function withTo($to)
	{
		if($this->isValidEmailAddress($to))
		{
			$this->to = $to;
			return $this;
		}
		else
		{
			throw new Exception('The \'to\' address was not valid.');
		}
	}
	public function withFrom($from)
	{
		if($this->isValidEmailAddress($from))
		{
			$this->headers[] = 'From: '.$from;
			return $this;
		}
		else
		{
			throw new Exception('The \'from\' address was not valid.');
		}
	}
	public function addBcc($bcc)
	{
		if($this->isValidEmailAddress($bcc))
		{
			$this->headers[] = 'Bcc: '.$bcc;
			return $this;
		}
		else
		{
			throw new Exception('The \'bcc\' address was not valid.');
		}
	}
	public function addCc($cc)
	{
		if($this->isValidEmailAddress($cc))
		{
			$this->headers[] = 'Cc: '.$cc;
			return $this;
		}
		else
		{
			throw new Exception('The \'bcc\' address was not valid.');
		}
	}
	public function isValidEmailAddress($email)
	{
		return preg_match($this->emailRegex, $email);
	}
	public function isFreeOfHackemes($value)
	{
		foreach($this->hackemes as $hackeme)
		{
			if(!(stristr($value, $hackeme) === false))
			{
				return false;
			}
		}
		
		return true;
	}
	public function run()
	{
		$b = "\r\n";
		$headers = "";
		
		foreach($this->headers as $header)
		{
			$headers .= $header.$b;
		}
		
		return mail($this->to, $this->subject, $this->message, $headers);
	}
}

?>